/*
 * Copyright (c) 2006-2019, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-05-24                  the first version
 */

#include <rthw.h>
#include <rtthread.h>
#include "bsp_usart1.h"
#include "bsp_systick.h"

#if defined(RT_USING_USER_MAIN) && defined(RT_USING_HEAP)
/*
 * Please modify RT_HEAP_SIZE if you enable RT_USING_HEAP
 * the RT_HEAP_SIZE max value = (sram size - ZI size), 1024 means 1024 bytes
 */
#define RT_HEAP_SIZE (15*1024)
static rt_uint8_t rt_heap[RT_HEAP_SIZE];

RT_WEAK void *rt_heap_begin_get(void)
{
    return rt_heap;
}

RT_WEAK void *rt_heap_end_get(void)
{
    return rt_heap + RT_HEAP_SIZE;
}
#endif

void rt_os_tick_callback(void)
{
    rt_interrupt_enter();
    
    rt_tick_increase();

    rt_interrupt_leave();
}

/**
 * This function will initial your board.
 */
void rt_hw_board_init(void)
{
#ifdef RT_USING_COMPONENTS_INIT
    rt_components_board_init();
#endif

#if defined(RT_USING_USER_MAIN) && defined(RT_USING_HEAP)
    rt_system_heap_init(rt_heap_begin_get(), rt_heap_end_get());
#endif
}

#ifdef RT_USING_CONSOLE

static int uart_init(void)
{
	Usart1_Init();
    return 0;
}
INIT_BOARD_EXPORT(uart_init);


void rt_hw_console_output(const char *str) 
{
  	rt_enter_critical();
	
	while(*str!='\0')
	{
		if (*str == '\n')
		{
			USART_SendData(USART1, '\r');
			while(USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);
		}
		USART_SendData(USART1, *(str++));
	  	while(USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);
	}

  	rt_exit_critical(); 
	
}

char rt_hw_console_getchar(void)
{
    /* Note: the initial value of ch must < 0 */
	int ch = -1;
	if(Queue_isEmpty(&queue_usart)) return ch;
	Queue_pop(&queue_usart, (char *)&ch);
    return ch;
}


#endif

void SysTick_Handler(void) 
{
	G_Timer_Tick++;
	rt_os_tick_callback();
}

